package yxy.game.pm2.command.godBeast;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PickedGodBeastMessage;
import yxy.game.pm2.module.godBeast.GodBeast;
import yxy.game.pm2.module.godBeast.PickedGodBeastHandle;
import yxy.game.pm2.module.godBeast.PickedGodBeastModule;

/**
 * @name CMD_PickedGodBeastToFormat
 * @author wrs
 * @descrition 神兽上阵
 * @since 2022-06-17
 */
@MessageType(proto = Command.PickedGodBeastToFormat,classtype = PickedGodBeastMessage.PickedGodBeastToFormatRequest.class)
public class CMD_PickedGodBeastToFormat extends Command<PickedGodBeastMessage.PickedGodBeastToFormatRequest> {

    @Override
    public void execute(MessageSource messageSource, PickedGodBeastMessage.PickedGodBeastToFormatRequest request) throws Exception {
        String playerCode = messageSource.getTag();
        int therionId = request.getCode(); //神兽ID
        boolean isChecked = request.getIsChecked(); //是否勾选上阵

        PickedGodBeastMessage.PickedGodBeastToFormatResponse.Builder response = PickedGodBeastMessage.PickedGodBeastToFormatResponse.newBuilder();

        try {
            PickedGodBeastModule module = PickedGodBeastModule.get(playerCode);
            if (module == null){
                send(messageSource,response, Result.DataError);
                return;
            }

            PickedGodBeastModule godBeastModule = PickedGodBeastModule.get(playerCode);
            if (godBeastModule == null){
                send(messageSource,response, Result.DataError);
                return;
            }

            //选择的神兽上阵状态，其他下阵
            for (GodBeast godBeast : godBeastModule.getGbs().values()) {
                int godBeastCode = godBeast.getCode(); //神兽id
                boolean isBattle = godBeast.isBattle(); //是否上阵

                if(godBeastCode != therionId && isBattle){
                    godBeast.setBattle(false);
                    continue;
                }

                if (godBeastCode == therionId){
                    godBeast.setBattle(isChecked);
                    continue;
                }
            }

            godBeastModule.set();

            for (GodBeast godBeast : godBeastModule.getGbs().values()) {
                response.addGbs(new PickedGodBeastHandle().getGodBeasts(playerCode,godBeast));
            }

            send(messageSource,response, Result.Success);

        }catch (Exception e){
            e.printStackTrace();
            send(messageSource,response, Result.DataError);
        }
    }

    private void send(MessageSource messageSource, PickedGodBeastMessage.PickedGodBeastToFormatResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}
